
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <Wire.h>
#include "Adafruit_SGP30.h"
#include <PubSubClient.h>
#include <ArduinoJson.h>

const char *ssid = "EASYSTACK-ZZ";
const char *password = "Easystack@0930zz.com";
const char *URL = "http://192.168.5.207:3000/test";

Adafruit_SGP30 sgp;
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);

void setup() {
  Serial.begin(9600); //通信串口波特率

  intiWifi();
  if (! sgp.begin()) {
    Serial.println("未找到SGP传感器");
    while (1);
  }
}

void loop() {
  getAQI();
  postData();
  delay(2000);
}

//获取控制质量
void getAQI() {
  if (! sgp.IAQmeasure()) {
    Serial.println("Measurement failed");
    return;
  }
  Serial.print("TVOC "); Serial.print(sgp.TVOC); Serial.println(" ppb\t");
  Serial.print("eCO2 "); Serial.print(sgp.eCO2); Serial.println(" ppm");
}

//初始化WIFI
void intiWifi() {
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(1000);
    Serial.println("正在连接中");
  }

  Serial.println("您的开发板的IP:");
  Serial.println(WiFi.localIP());
}

void postData() {
  HTTPClient httpClient;          //1、创建http的客户端

  httpClient.begin(wifiClient, URL); //2、通过begin函数配置请求地址。此处也可以不使用端口号
  Serial.print("URL: ");
  Serial.println(URL);
  httpClient.addHeader("Content-Type", "application/json");

  //创建JSON
  DynamicJsonDocument doc(1024);
  doc.as<JsonObject>();
  doc["tvoc"] = sgp.TVOC;
  doc["co2"] = sgp.eCO2;
  String output;
  serializeJson(doc, output);
  Serial.println(output);
  
  int httpCode = httpClient.POST(output);
  if (httpCode > 0) {
    Serial.printf("[HTTP] GET... code: %d\n", httpCode);
    if (httpCode == HTTP_CODE_OK) {
      String payload = httpClient.getString();    //获取响应体
      Serial.println(payload);
    } else {
      Serial.printf("请求失败 %s\n", httpClient.errorToString(httpCode).c_str());
    }
  } else {
    Serial.printf("[HTTP] Unable to connect\n");
  }
  httpClient.end();
}
